<template>
  <a-modal
    :open="props.visible"
    :title="isEdit ? '编辑项目' : '创建项目'"
    :confirm-loading="loading"
    @ok="onSubmit"
    @cancel="onCancel"
    @update:open="(val: boolean) => emit('update:visible', val)"
    width="800px"
    :maskClosable="false"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      layout="vertical"
    >
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="项目名称" name="name">
            <a-input v-model:value="formData.name" placeholder="请输入项目名称" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="项目分组" name="groupId">
            <a-select v-model:value="formData.groupId" placeholder="请选择项目分组">
              <a-select-option 
                v-for="group in groups" 
                :key="group.id" 
                :value="group.id"
              >
                {{ group.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item label="项目描述" name="description">
        <a-textarea 
          v-model:value="formData.description" 
          placeholder="请输入项目描述"
          :rows="3"
        />
      </a-form-item>

      <a-form-item label="环境配置">
        <div class="environments-config">
          <div 
            v-for="(env, index) in formData.environments" 
            :key="index"
            class="environment-item"
          >
            <a-card size="small" :title="`环境 ${index + 1}`">
              <template #extra>
                <a-button 
                  type="link" 
                  danger 
                  size="small"
                  @click="removeEnvironment(index)"
                  :disabled="formData.environments.length <= 1"
                >
                  删除
                </a-button>
              </template>

              <a-row :gutter="12">
                <a-col :span="8">
                  <a-form-item 
                    :name="['environments', index, 'name']"
                    :rules="[{ required: true, message: '请输入环境名称' }]"
                  >
                    <a-input 
                      v-model:value="env.name" 
                      placeholder="环境名称"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item 
                    :name="['environments', index, 'type']"
                    :rules="[{ required: true, message: '请选择环境类型' }]"
                  >
                    <a-select v-model:value="env.type" placeholder="环境类型">
                      <a-select-option value="development">开发环境</a-select-option>
                      <a-select-option value="test">测试环境</a-select-option>
                      <a-select-option value="preview">预发布环境</a-select-option>
                      <a-select-option value="production">正式环境</a-select-option>
                      <a-select-option value="custom">自定义环境</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item>
                    <a-input 
                      v-model:value="env.description" 
                      placeholder="环境描述（可选）"
                    />
                  </a-form-item>
                </a-col>
              </a-row>

              <a-form-item 
                label="Host配置"
                :name="['environments', index, 'hosts']"
                :rules="[{ required: true, message: '请添加至少一个Host配置' }]"
              >
                <div class="hosts-config">
                  <div 
                    v-for="(_host, hostIndex) in env.hosts" 
                    :key="hostIndex"
                    class="host-item"
                  >
                    <a-input 
                      v-model:value="env.hosts[hostIndex]" 
                      placeholder="如：127.0.0.1:8080 dev.example.com"
                      style="flex: 1;"
                    />
                    <a-button 
                      type="link" 
                      danger 
                      @click="removeHost(index, hostIndex)"
                      :disabled="env.hosts.length <= 1"
                    >
                      删除
                    </a-button>
                  </div>
                  <a-button 
                    type="dashed" 
                    @click="addHost(index)"
                    style="width: 100%;"
                  >
                    + 添加Host配置
                  </a-button>
                </div>
              </a-form-item>
            </a-card>
          </div>

          <a-button 
            type="dashed" 
            @click="addEnvironment"
            style="width: 100%; margin-top: 16px;"
          >
            + 添加环境
          </a-button>
        </div>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, watch, nextTick } from 'vue';
import { message } from 'ant-design-vue';
import type { FormInstance } from 'ant-design-vue';
import type { ProjectFormData, ProjectGroup, Project, EnvironmentType } from '@/types';
import { projectApi } from '@/api';

// Props
interface Props {
  visible: boolean;
  groups: ProjectGroup[];
  editProject?: Project | null;
}

const props = withDefaults(defineProps<Props>(), {
  editProject: null,
});

// Emits
const emit = defineEmits<{
  'update:visible': [value: boolean];
  success: [];
}>();

// 响应式数据
const formRef = ref<FormInstance>();
const loading = ref(false);

const defaultEnvironment = () => ({
  name: '',
  type: 'development' as EnvironmentType,
  hosts: [''],
  description: '',
});

const formData = reactive<ProjectFormData>({
  name: '',
  description: '',
  groupId: '',
  environments: [defaultEnvironment()],
});

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
  groupId: [{ required: true, message: '请选择项目分组', trigger: 'change' }],
  description: [{ required: false }],
};

// 计算属性
const isEdit = ref(false);

// 监听弹窗显示状态
watch(() => props.visible, (newVal) => {
  if (newVal) {
    resetForm();
    if (props.editProject) {
      loadEditData();
    }
  }
});

// 重置表单
const resetForm = () => {
  isEdit.value = !!props.editProject;
  Object.assign(formData, {
    name: '',
    description: '',
    groupId: '',
    environments: [defaultEnvironment()],
  });
  
  nextTick(() => {
    formRef.value?.clearValidate();
  });
};

// 加载编辑数据
const loadEditData = () => {
  if (props.editProject) {
    Object.assign(formData, {
      name: props.editProject.name,
      description: props.editProject.description,
      groupId: props.editProject.groupId,
      environments: props.editProject.environments.map(env => ({
        name: env.name,
        type: env.type,
        hosts: [...env.hosts],
        description: env.description || '',
      })),
    });
  }
};

// 添加环境
const addEnvironment = () => {
  formData.environments.push(defaultEnvironment());
};

// 删除环境
const removeEnvironment = (index: number) => {
  if (formData.environments.length > 1) {
    formData.environments.splice(index, 1);
  }
};

// 添加Host配置
const addHost = (envIndex: number) => {
  formData.environments[envIndex].hosts.push('');
};

// 删除Host配置
const removeHost = (envIndex: number, hostIndex: number) => {
  const env = formData.environments[envIndex];
  if (env.hosts.length > 1) {
    env.hosts.splice(hostIndex, 1);
  }
};

// 提交表单
const onSubmit = async () => {
  try {
    await formRef.value?.validate();
    
    // 过滤空的host配置
    const cleanedData = {
      ...formData,
      environments: formData.environments.map(env => ({
        ...env,
        hosts: env.hosts.filter(host => host.trim()),
      })),
    };

    // 验证每个环境至少有一个host
    for (const env of cleanedData.environments) {
      if (env.hosts.length === 0) {
        message.error(`环境"${env.name}"至少需要一个Host配置`);
        return;
      }
    }

    loading.value = true;

    if (isEdit.value && props.editProject) {
      await projectApi.update(props.editProject.id, cleanedData);
      message.success('项目更新成功');
    } else {
      await projectApi.create(cleanedData);
      message.success('项目创建成功');
    }

    emit('success');
    onCancel();
  } catch (error: any) {
    message.error(error.message || '操作失败');
  } finally {
    loading.value = false;
  }
};

// 取消
const onCancel = () => {
  emit('update:visible', false);
};
</script>

<style scoped>
.environments-config {
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  padding: 16px;
  background-color: #fafafa;
}

.environment-item {
  margin-bottom: 16px;
}

.environment-item:last-child {
  margin-bottom: 0;
}

.hosts-config {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.host-item {
  display: flex;
  align-items: center;
  gap: 8px;
}
</style>
